import axios from 'axios';
import { LoginRequest, RegisterRequest, UpdateUserRequest, User, UserQuery } from '../types/user';

// API基础URL
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8080/api';

// 用户API
export const userApi = {
  /**
   * 用户登录
   */
  login: async (data: LoginRequest) => {
    const response = await axios.post(`${API_BASE_URL}/auth/login`, data);
    return response.data;
  },

  /**
   * 用户注册
   */
  register: async (data: RegisterRequest) => {
    const response = await axios.post(`${API_BASE_URL}/auth/register`, data);
    return response.data;
  },

  /**
   * 用户登出
   */
  logout: async () => {
    const response = await axios.post(`${API_BASE_URL}/auth/logout`);
    return response.data;
  },

  /**
   * 获取当前用户信息
   */
  getCurrentUser: async () => {
    const response = await axios.get(`${API_BASE_URL}/users/current`);
    return response.data;
  },

  /**
   * 更新用户信息
   */
  updateUser: async (id: number, data: UpdateUserRequest) => {
    const response = await axios.put(`${API_BASE_URL}/users/${id}`, data);
    return response.data;
  },

  /**
   * 获取所有用户
   */
  getAllUsers: async (params?: UserQuery) => {
    const response = await axios.get(`${API_BASE_URL}/users`, { params });
    return response.data;
  },

  /**
   * 获取单个用户
   */
  getUserById: async (id: number) => {
    const response = await axios.get(`${API_BASE_URL}/users/${id}`);
    return response.data;
  },

  /**
   * 修改用户状态
   */
  updateUserStatus: async (id: number, status: 'ACTIVE' | 'LOCKED' | 'INACTIVE') => {
    const response = await axios.patch(`${API_BASE_URL}/users/${id}/status`, { status });
    return response.data;
  },

  /**
   * 上传头像
   */
  uploadAvatar: async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);

    const response = await axios.post(`${API_BASE_URL}/users/avatar`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data;
  },

  /**
   * 重置密码
   */
  resetPassword: async (email: string) => {
    const response = await axios.post(`${API_BASE_URL}/auth/reset-password`, { email });
    return response.data;
  },

  /**
   * 确认重置密码
   */
  confirmResetPassword: async (token: string, newPassword: string) => {
    const response = await axios.post(`${API_BASE_URL}/auth/confirm-reset-password`, {
      token,
      newPassword,
    });
    return response.data;
  },
}; 